package com.dalongxin.work.page;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.andview.refreshview.utils.LogUtils;
import com.dalongxin.work.Constants;
import com.dalongxin.work.DataHelper;
import com.dalongxin.work.R;
import com.dalongxin.work.data.CloudDisk;
import com.dalongxin.work.page.adapter.CloudDiskAdapter;
import com.dalongxin.work.utils.FileUtils;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.StatusUtils;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.view.CloudDiskNewFolderDialog;
import com.dalongxin.work.view.MyCommonDialog;
import com.downloader.Error;
import com.downloader.OnCancelListener;
import com.downloader.OnDownloadListener;
import com.downloader.OnPauseListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.PRDownloaderConfig;
import com.downloader.Progress;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

/**
 * 云盘 档案管理
 */
@ContentView(R.layout.activity_cloud_disk)
public class CloudDiskActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private final static String TAG = "CloudDiskActivity";
    private static final int REQ_CHOOSE = 1001;

    private int mPage = 1;
    private int mCurrFileType = -1; //0:图片 1:音频 2:视频 3:txt 4:pdf 5、word 6、excel 7、其它 、8.文档 9.应用 -1全部
    private int mLastFileType = -1;
    private int mSortRule; //排序规则 0.文件名排序 1.时间顺序 2.时间倒序
    private int mLastSortRule = 99;
    private String mCurrFolder = "0";
    private int role = 1;
    private String mSearchContent = "";

    private List<CloudDisk> mDatas;
    private CloudDiskAdapter mAdapter;
    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.recycler_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.xrefreshview)
    private XRefreshView xRefreshView;

    private Callback.Cancelable uploadCall;
    private PopupWindow mPopupWindow;
    private View mPopupView;
    private PopupWindow mSortPop;

    private View mNoDataImg;
    private TextView mNormalTipsView;
    private LinearLayout mSpecialLayout;
    private TextView mFirstTipsView;
    private TextView mSecondTipsView;

    private CheckBox mSelAllCb;

    private Stack<String> mFolderStack = new Stack<>(); //文件夹栈
    private String mSuffix; //上传文件的后缀名

    public void setCurrFolder(String currFolder) {
        mCurrFolder = currFolder;
        mFolderStack.push(currFolder);
    }

    public View getNoDataImg() {
        return mNoDataImg;
    }

    public void setPage(int page) {
        mPage = page;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        this.setSupportActionBar(toolbar);//这样menu才能显示出来
        getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);

        mFolderStack.push(mCurrFolder);
        titleText.setText("网盘");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFolderStack.size() > 1) {
                    mPage = 1;
                    mFolderStack.pop();
                    mCurrFolder = mFolderStack.peek();
                    mCurrFileType = -1;
                    getCloudDiskList();
                } else {
                    finish();
                }
            }
        });
        //初始化文件下载
        // Enabling database for resume support even after the application is killed:
        // Setting timeout globally for the download network requests:
        PRDownloaderConfig config = PRDownloaderConfig.newBuilder()
                .setDatabaseEnabled(true)
                .setReadTimeout(30_000)
                .setConnectTimeout(30_000)
                .build();
        PRDownloader.initialize(getApplicationContext(), config);

        initTopMenu();
        initBatchOperateBtn();
        initEmptyView();

        mDatas = new ArrayList<>();
        mAdapter = new CloudDiskAdapter(CloudDiskActivity.this, this, role, mDatas, mSelAllCb);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(mAdapter);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        //xRefreshView1.setAutoLoadMore(true);
        mAdapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        //设置静默加载时提前加载的item个数
        //xRefreshView1.setPreLoadCount(4);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                mPage = 1;
                mAdapter.pauseAllDownload();
                mAdapter.clearDownloadMap();
                getCloudDiskList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                mPage++;
                getCloudDiskList();
            }
        });
        xRefreshView.setPullRefreshEnable(true);//允许下拉刷新
        xRefreshView.setPullLoadEnable(false);//禁止加载更多
        xRefreshView.setEmptyView(mNoDataImg);
        xRefreshView.setAutoRefresh(true);
        registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        requestPermission();
    }

    private void requestPermission() {
        EasyPermissions.requestPermissions(
                new PermissionRequest.Builder(this, 1, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .setRationale("需要您允许存储权限的申请")
                        .setPositiveButtonText("同意")
                        .setNegativeButtonText("拒绝")
                        .build());
    }

    private void initEmptyView() {
        mNoDataImg = findViewById(R.id.image_no_data);
        mNormalTipsView = (TextView) findViewById(R.id.normal_tips_view);
        mSpecialLayout = (LinearLayout) findViewById(R.id.special_layout);
        mFirstTipsView = (TextView) findViewById(R.id.first_tips);
        mSecondTipsView = (TextView) findViewById(R.id.second_tips);
        mNormalTipsView.setVisibility(View.GONE);
        mSpecialLayout.setVisibility(View.VISIBLE);
        mFirstTipsView.setText(getString(R.string.class_cloud_disk_empty_first_tips));
        mSecondTipsView.setText(getString(R.string.class_cloud_disk_empty_second_tips));
    }

    private void noMoreTip() {
        Toast.makeText(this, "已经到底了", Toast.LENGTH_SHORT).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void showConfirmDialog(final String fileIds, final String folderIds, final List<Integer> positions){
        final MyCommonDialog commonDialog = new MyCommonDialog(this, "提示消息", "确认删除吗？", "取消", "确认");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing())
                    commonDialog.dismiss();
                mAdapter.deleteClassroomNetDiskFile(fileIds, folderIds, positions, true);
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    private void initBatchOperateBtn() {
        mSelAllCb = (CheckBox) findViewById(R.id.sel_all_checkbox);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                StringBuilder fileIds = new StringBuilder();
                StringBuilder folderIds = new StringBuilder();
                List<Integer> positions = new ArrayList<>();
                for (CloudDisk cd : mDatas) {
                    if (cd.isChecked()) {
                        if (cd.isFolder()) {
                            folderIds.append(cd.getFileId()).append(",");
                        } else {
                            fileIds.append(cd.getFileId()).append(",");
                        }
                        positions.add(mDatas.indexOf(cd));
                    }
                }

                switch (v.getId()) {
                    case R.id.sel_all_tv: //全选
                        mSelAllCb.setChecked(!mSelAllCb.isChecked());
                    case R.id.sel_all_checkbox: //全选
                        List<CloudDisk> datas = mAdapter.getDatas();
                        for (CloudDisk cd : datas) {
                            cd.setChecked(mSelAllCb.isChecked());
                        }
                        mAdapter.setDataAndNotify(datas);
                        break;
                    case R.id.edit_move_tv: //批量移动
                        if (fileIds.length() + folderIds.length() == 0) {
                            ToastUtil.showShort(CloudDiskActivity.this, getResources().getString(R.string.no_selected_move_tip));
                        } else {
                            if (fileIds.length() > 0) {
                                fileIds.deleteCharAt(fileIds.length() - 1);
                            }
                            if (folderIds.length() > 0) {
                                folderIds.deleteCharAt(folderIds.length() - 1);
                            }
                            int requestCode = CloudDiskChooseFolderActivity.MOVE_REQUEST_CODE;
                            //startActivityForResult为了移动完刷新列表
                            startActivityForResult(CloudDiskChooseFolderActivity.newIntent(CloudDiskActivity.this, fileIds.toString(), folderIds.toString()), requestCode);
                        }
                        break;
                    case R.id.edit_delete_tv: //批量删除
                        if (fileIds.length() + folderIds.length() == 0) {
                            ToastUtil.showShort(CloudDiskActivity.this, getResources().getString(R.string.no_selected_delete_tip));
                        } else {
                            if (fileIds.length() > 0) {
                                fileIds.deleteCharAt(fileIds.length() - 1);
                            }
                            if (folderIds.length() > 0) {
                                folderIds.deleteCharAt(folderIds.length() - 1);
                            }
                            showConfirmDialog(fileIds.toString(), folderIds.toString(), positions);
                        }
                        break;
                    case R.id.edit_cancel_tv: //取消
                        setBatchEditState(false);
                        break;
                    default:
                        break;
                }
            }
        };
        findViewById(R.id.sel_all_tv).setOnClickListener(onClickListener);
        mSelAllCb.setOnClickListener(onClickListener);
        findViewById(R.id.edit_move_tv).setOnClickListener(onClickListener);
        findViewById(R.id.edit_delete_tv).setOnClickListener(onClickListener);
        findViewById(R.id.edit_cancel_tv).setOnClickListener(onClickListener);
    }

    public void setSelAllBtnSelected() {
        if (mSelAllCb != null) {
            mSelAllCb.setChecked(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cloud_disk, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem diskNew = menu.findItem(R.id.menu_new);
        MenuItem diskUpload = menu.findItem(R.id.menu_upload);
        diskNew.setVisible(true);
        diskUpload.setVisible(true);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_new:
                setBatchEditState(false);
                CloudDiskNewFolderDialog dialog = new CloudDiskNewFolderDialog(CloudDiskActivity.this, CloudDiskActivity.this, mCurrFolder);
                dialog.show();
                break;
            case R.id.menu_upload:
                Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                innerIntent.setType("*/*"); // 查看类型
                Intent wrapperIntent = Intent.createChooser(innerIntent, "选择文件");
                startActivityForResult(wrapperIntent, REQ_CHOOSE);
                setBatchEditState(false);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initTopMenu() {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.sort_layout: //排序
                        mSortPop = new PopupWindow(CloudDiskActivity.this);
                        View popupView = LayoutInflater.from(CloudDiskActivity.this).inflate(R.layout.fragment_popup_cloud_disk_sort, null);
                        initSortBtn(popupView);
                        mSortPop.setContentView(popupView);
                        mSortPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                        mSortPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                        mSortPop.setOutsideTouchable(true);
                        mSortPop.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00FFFFFF")));
                        int yOff = findViewById(R.id.relativelayout1).getHeight() + findViewById(R.id.top_menu_layout).getHeight();
                        mSortPop.showAsDropDown(v, 0, -yOff);
                        setBatchEditState(false);
                        mAdapter.pauseAllDownload(); //如果有文件下载则暂停
                        mAdapter.clearDownloadMap();
                        break;
                    case R.id.new_folder_layout: //新建文件夹
                        setBatchEditState(false);
                        CloudDiskNewFolderDialog dialog = new CloudDiskNewFolderDialog(CloudDiskActivity.this, CloudDiskActivity.this, mCurrFolder);
                        dialog.show();
                        break;
                    case R.id.search_layout: //搜索
                        setBatchEditState(false);
                        /*Intent intent = new Intent(CloudDiskActivity.this, CloudDiskSearchActivity.class);
                        intent.putExtra(CloudDiskSearchActivity.EXTRA_CLASSROOM, mClassroom);
                        intent.putExtra(CloudDiskSearchActivity.EXTRA_CLASS_ID, mClassId);
                        startActivityForResult(intent, CloudDiskSearchActivity.REQUEST_SEARCH);*/
                        break;
                    case R.id.edit_layout: //编辑
                        setBatchEditState(!mAdapter.isEditing());
                        mAdapter.pauseAllDownload();
                        break;
                    default:
                        break;
                }
            }

            private void initSortBtn(View popupView) {
                View.OnClickListener onClickListener1 = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) { //排序规则 0.文件名排序 1.时间顺序 2.时间倒序
                            case R.id.file_name_sort_tv:
                                mSortRule = 0;
                                break;
                            case R.id.time_sort_tv:
                                mSortRule = 1;
                                break;
                            case R.id.time_reverse_sort_tv:
                                mSortRule = 2;
                                break;
                            default:
                                break;
                        }
                        if (mLastSortRule == mSortRule) { //防止重复点击
                            mSortPop.dismiss();
                            return;
                        }
                        mLastSortRule = mSortRule;
                        mPage = 1;
                        getCloudDiskList();
                        mSortPop.dismiss();
                    }
                };
                popupView.findViewById(R.id.file_name_sort_tv).setOnClickListener(onClickListener1);
                popupView.findViewById(R.id.time_sort_tv).setOnClickListener(onClickListener1);
                popupView.findViewById(R.id.time_reverse_sort_tv).setOnClickListener(onClickListener1);

                popupView.findViewById(R.id.outside_layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSortPop.dismiss();
                    }
                });
            }
        };
        findViewById(R.id.sort_layout).setOnClickListener(onClickListener);
        findViewById(R.id.new_folder_layout).setOnClickListener(onClickListener);
        findViewById(R.id.search_layout).setOnClickListener(onClickListener);
        findViewById(R.id.edit_layout).setOnClickListener(onClickListener);
    }

    public void setBatchEditState(boolean isEditing) {
        mAdapter.setEditing(isEditing);
        mAdapter.notifyDataSetChanged();
        if (isEditing) {
            xRefreshView.setPullRefreshEnable(false);
            xRefreshView.setPullLoadEnable(false);
            findViewById(R.id.batch_operate_layout).setVisibility(View.VISIBLE);
        } else {
            xRefreshView.setPullRefreshEnable(true);
            xRefreshView.setPullLoadEnable(false);
            findViewById(R.id.batch_operate_layout).setVisibility(View.GONE);
            for (CloudDisk cd : mAdapter.getDatas()) {
                cd.setChecked(false);
            }
            mSelAllCb.setChecked(false);
        }
    }

    private void folderStackInit() {
        mFolderStack.clear();
        mFolderStack.push("0");
    }

    public CloudDiskAdapter getAdapter() {
        return mAdapter;
    }

    public void getCloudDiskList() {
        HashMap<String, String> params = new HashMap<>();
        params.put("folderId", mCurrFolder);
        //params.put("page", mPage + "");
        LogUtils.i(TAG + " classroomNetDisk 接口参数：\n" + params.toString());
        HttpUtil.getInstance().post(true, Constants.url_getMyFolderList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                xRefreshView.stopRefresh();
                LogUtils.i(TAG + " classroomNetDisk 接口返回：\n" + response.toString());
                if (response.optInt("ret") == 0) {
                    try {
                        List<CloudDisk> datas = CloudDisk.parseFolderFromJsonList(response.optJSONObject("data").optJSONArray("folderList"), false);
                        List<CloudDisk> files = CloudDisk.parseFromJsonList(response.optJSONObject("data").optJSONArray("fileList"));
                        datas.addAll(files);
                        if (datas.size() == 0) {
                            if (mPage > 1) {
                                noMoreTip();
                            } else {
                                mDatas.clear();
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                        if (mPage == 1) {
                            mDatas.clear();
                            try { //删除本地数据
                                DataHelper.getHelper(CloudDiskActivity.this).getCloudDiskDao().deleteBuilder().delete();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                        if (datas.size() > 0) {
                            mNoDataImg.setVisibility(View.GONE);
                            for (CloudDisk item : datas) {
                                try { //保存到本地数据库
                                    DataHelper.getHelper(CloudDiskActivity.this).getCloudDiskDao().create(item);
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                                //记录未读状态
                                recordUnreadState(item);
                            }
                            mDatas.addAll(datas);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            if (mPage == 1) {
                                mNoDataImg.setVisibility(View.VISIBLE);
                            } else {
                                mPage--;
                            }
                        }
                    } catch (Exception ex) {
                        Log.e(TAG, ex.getMessage());
                    }
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (mPage > 1) {
                    mPage--;
                }
                xRefreshView.stopRefresh();
                StatusUtils.handleError(ex, CloudDiskActivity.this);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

    private void recordUnreadState(CloudDisk item) {
        SharedPreferences sp = getSharedPreferences(getString(R.string.cloud_disk_title) + "-" +
                getDefaultAccount().getId(), Context.MODE_PRIVATE);
        if (TextUtils.isEmpty(sp.getString(item.getFileId(), ""))) {
            SharedPreferences.Editor ed = sp.edit();
            ed.putString(item.getFileId(), Constants.Key.SP_CLOUD_DISK_UNREAD);
            ed.putInt(Constants.Key.SP_CLOUD_DISK_COUNT, sp.getInt(Constants.Key.SP_CLOUD_DISK_COUNT, 0) + 1);
            ed.apply();
            /*Intent intent = new Intent(ClassContainActivity.BROADCAST_ACTION_NEW_SHUOSHUO);
            intent.putExtra(ClassContainActivity.BROAD_FOR_WHAT, ClassContainActivity.BROAD_FOR_CLOUD_DISK);
            CloudDiskActivity.this.sendBroadcast(intent);*/
        }
    }

    public static void start(Context context, long classId) {
        Intent intent = new Intent(context, CloudDiskActivity.class);
        intent.putExtra("classId", classId);
        context.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    xRefreshView.stopRefresh();
                    break;
            }
        }
    };

    //监听下载完成
    private BroadcastReceiver mDownloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                //在广播中取出下载任务的id
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                mAdapter.updateView((LinearLayoutManager)recyclerView.getLayoutManager(), id);
            }
        }
    };

    public int download(String url, String dirPath, String fileName) {

        int downloadId = PRDownloader.download(url, dirPath, fileName).build()
            .setOnStartOrResumeListener(new OnStartOrResumeListener() {
                @Override
                public void onStartOrResume() {

                }
            })
            .setOnPauseListener(new OnPauseListener() {
                @Override
                public void onPause() {

                }
            })
            .setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel() {

                }
            })
            .setOnProgressListener(new OnProgressListener() {
                @Override
                public void onProgress(Progress progress) {

                }
            })
            .start(new OnDownloadListener() {

                @Override
                public void onDownloadComplete() {

                }

                @Override
                public void onError(Error error) {

                }
            });
        return downloadId;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CHOOSE && resultCode == Activity.RESULT_OK) {
            String path = FileUtils.getPath(CloudDiskActivity.this, data.getData());
            final File file = new File(path);
            long limit = 1024 * 1024 * 50;
            LogUtils.i(TAG + " file.length = " + file.length() + "B, 50M = " + limit + "B");
            if (file.length() > limit) {
                Toast.makeText(CloudDiskActivity.this, "文件大于50M,暂不能上传", Toast.LENGTH_SHORT).show();
                return;
            }

            final String fileType = FileUtils.getSimpleFileType(file.getName());
            final String fileName = checkFileName(file.getName());
            //ProgressDialogUtils.showProgressDialog("正在上传附件，请稍候", CloudDiskActivity.this, false);
            uploadFile(file, fileType, fileName);
        } else if (requestCode == CloudDiskChooseFolderActivity.MOVE_REQUEST_CODE && resultCode == CloudDiskChooseFolderActivity.MOVE_CLOUD_DISK_FRAGMENT_RESULT_CODE) {
            setBatchEditState(false);
            mAdapter.clearDownloadMap();
            getCloudDiskList();
        }/* else  if (requestCode == CloudDiskSearchActivity.REQUEST_SEARCH && resultCode == CloudDiskSearchActivity.RESULT_SEARCH) {
            getCloudDiskList();
        }*/
    }

    private void uploadFile(final File file, final String fileType, String fileName) {
        /*
            filetype	√	int	    0:图片 1:音频 2:视频 3:txt 4:pdf 5、word 6、excel 7、其它 8.文档 9.应用
            fileName	√	String	文件名
            classroomId	√	int	    班级ID
            folderId	√	String  文件夹id 注:-1代表上传到根目录
            videoPicUrl	√	String	视频截图url
         */
        showUploadDialog();
        final ProgressBar progressBar = (ProgressBar) mPopupView.findViewById(R.id.progress_bar);
        final TextView progressTv = (TextView) mPopupView.findViewById(R.id.progress_tv);
        Map<String, String> params = new HashMap<>();
        params.put("folderId", mCurrFolder);
        uploadCall = HttpUtil.getInstance().uploadFile(true, Constants.url_uploadFile, file, params, new Callback.ProgressCallback<JSONObject>() {
            @Override
            public void onSuccess(final JSONObject response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (response.optInt("ret") == 0) {
                            mPage = 1;
                            mAdapter.clearDownloadMap();
                            getCloudDiskList();
                        } else {
                            StatusUtils.handleStatus(response, CloudDiskActivity.this);
                            mPopupWindow.dismiss();
                        }
                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.i(TAG + " OkHttpUpload.UploadListener onFailure 上传失败！");
                        ToastUtil.showShort(CloudDiskActivity.this, "上传失败！");
                    }
                });
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPopupWindow.dismiss();
                    }
                });
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(final long total, final long current, boolean isDownloading) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int progress = (int) (current * 100 / total);
                        LogUtils.i(TAG + " 上传进度：" + progress + "% totalBytes:" + total + " uploadedBytes:" + current + " remainingBytes:" + (total - current));
                        progressBar.setProgress(progress);
                        progressTv.setText(progress + "%");
                    }
                });
            }
        });
    }
    private void showUploadDialog() {
        mPopupView = LayoutInflater.from(this).inflate(R.layout.dialog_upload_file, null);
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        mPopupWindow = new PopupWindow(mPopupView, width, height, true);
        View parent = getWindow().getDecorView().findViewById(android.R.id.content);
        mPopupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        mPopupView.findViewById(R.id.upload_cancel_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(uploadCall != null && !uploadCall.isCancelled()) {
                    uploadCall.cancel();
                }
                ToastUtil.showShort(CloudDiskActivity.this, "取消上传！");
                mPopupWindow.dismiss();
            }
        });
    }

    private String checkFileName(String name) {
        mSuffix = "";
        //如果除去后缀长度大于20，截取20个字符，不加后缀；除去后缀小于20，返回不加后缀的文件名
        if (name.length() <= 20) {
            return name;
        }
        int index = name.lastIndexOf('.');
        if (index >= 0) {
            String noSuffix = name.substring(0, index);
            mSuffix = name.substring(index + 1);
            if (noSuffix.length() > 20) {
                return noSuffix.substring(0, 20);
            } else {
                return noSuffix;
            }
        } else {
            return name.substring(0, 20);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CloudDiskActivity.this.unregisterReceiver(mDownloadReceiver);
    }

    @Override
    public void onStart() {
        super.onStart();
   }

    @Override
    public void onStop() {
        super.onStop();
        mAdapter.pauseAllDownload();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToastUtil.showShort(CloudDiskActivity.this, "请选择权限申请允许后继续使用");
        finish();
    }
}
